package com.cgy.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.cgy.entity.Computer;
import com.cgy.entity.ConsumeLogs;
import com.cgy.repository.ComputerRepository;
import com.cgy.repository.ConsumeLogsRepository;

import util.FenyeUtil;
import util.PoiUtils;
import util.ResultUtil;

@RestController
@RequestMapping("/rizhi/excel")
public class rizhiExcel {
	@Autowired
	private ConsumeLogsRepository conR;
	
	@GetMapping
	public void testExcel(HttpServletResponse response, String ids) {
		String downloadName = "ConsumeLogs.xls";
		response.setCharacterEncoding("UTF-8");// 设置响应的字符编码格式
		response.setContentType("application/vnd.ms-excel");// 指明响应文件为excel类型
		ServletOutputStream out = null;
		try {
			// 文件名编码处理，防止浏览器下载文件名乱码
			response.setHeader("Content-disposition", "attachment;filename="
					+ new String(downloadName.getBytes("GB2312"), "ISO8859-1"));
			out = response.getOutputStream();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		List<ConsumeLogs> sList = new ArrayList<ConsumeLogs>();
		if(ids !=null && ids != "") {
			for(int i =0;i<ids.length();i++) {
				//同过遍历取出字符串里的每个id
				Integer cid = Integer.parseInt(String.valueOf(ids.charAt(i)));
				System.out.println(cid);
				Optional<ConsumeLogs> com = conR.findById(cid);
				sList.add(com.get());
			}
		}else {
			sList = conR.findAll();
		}
		
		try {
			PoiUtils p = new PoiUtils();
			p.createExcel(sList, ConsumeLogs.class, out);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping("/importExcel")
	public ResultUtil importExcel(@RequestParam(value = "file") MultipartFile file) {
		
		String originalFilename = file.getOriginalFilename();// 得到上传文件的名称
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		//把上传的Excel文件里的数据解析出来，调用方法，存入数据库
		PoiUtils poiUtils = new PoiUtils();// Excel工具类
		List<ConsumeLogs> list = null;
		ConsumeLogs cnsumeLogs = null;
		try {
			list = (List<ConsumeLogs>) poiUtils.parseExcel(Computer.class,
					file.getInputStream(), originalFilename);
			for (ConsumeLogs c : list) { 
				cnsumeLogs = conR.save(c);
			}
			return new ResultUtil(0, "成功"); 
		} catch (IOException e) {
			e.printStackTrace(); 
			return new ResultUtil(-1, "操作失败");
		}
	}		
}
